from core.itertools2 import column
from plyny.workstreams import Manager


if __name__ == '__main__':
    from easyconfig import Config
    c = Config()

    with c.parser() as p:
        p.add_option('sort-index', alias='s')
        p.add_flag('reverse', alias='r')
        p.set_mutually_exclusive(
            p.add_flag('latex'),
            p.add_flag('html'))
        p.add_option('workstream', alias='k', multiple=True, unspecified_default=True)

    wss = c.workstreams().open(workstream[0])

    if latex:
        from plyny.presentation.latex import LatexTable as Table
    elif html:
        from plyny.presentation.html import HtmlTable as Table
        print u'''<html>
<head>
<link rel="stylesheet" href="http://tablesorter.com/docs/css/jq.css" type="text/css" media="print, projection, screen" />
<link rel="stylesheet" href="http://tablesorter.com/themes/blue/style.css" type="text/css" media="print, projection, screen" />

<script type="text/javascript" src="http://tablesorter.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://tablesorter.com/jquery.tablesorter.js"></script>

<script type="text/javascript">
$(function() { 
    $("#myTable").tablesorter(); 
}) 
</script>
</head>
<body>
<table id="myTable" class="tablesorter">
'''

    else:
        from plyny.presentation.text import TextTable as Table

    if not isinstance(wss, list):
        wss = [wss]

    for ws in wss:
        if sort_index:
            ws.sort_by(sort_index, reverse)

        t = ws.table(Table)
        for i, typ in enumerate(ws.types()):
            if i == 0:
                continue

            if typ in (float, int):
                column = ws.columns(i)
                max, min = column.max(), column.min()

                if typ == float:
                    t.set_format(i, '%0.2f')

                    if min <= 0:
                        max += abs(min) + 1
                        min = 1

                    if max / min > 10:
                        t.set_format(i, '%0.0f')

                    if max / min > 10 and max > 1000000:
                        t.set_format(i, t.ABBREVIATE)

                elif typ == int:
                    if max > 1000000:
#                    if max / min > 10 and max > 1000000:
                        t.set_format(i, t.ABBREVIATE)

            t.set_justification(i, Table.RIGHT)

        print t.render().encode('utf-8', 'replace')

    if html:
        print '''</table>
</body>
</html>'''
